package com.coder520.common.security;

import com.coder520.common.Const;
import com.coder520.dao.UserMapper;
import com.coder520.pojo.Permission;
import com.coder520.pojo.Role;
import com.coder520.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by ASUS on 2017/7/13.
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;



    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        User user = userMapper.selectByUsername(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for(Role role:user.getRoles()){
            simpleAuthorizationInfo.addRole(role.getRole());
            for(Permission permission : role.getPermissions()){
                simpleAuthorizationInfo.addStringPermission(permission.getPermission());
            }
        }


        return simpleAuthorizationInfo;
    }

    /**
     * 认证登录
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        String username = usernamePasswordToken.getUsername();

        User user = userMapper.selectByUsername(username);
        if(user!=null){
            AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());

            SecurityUtils.getSubject().getSession().setAttribute(Const.CURRENT_USER,user);
            return info;
        }
        return null;
    }
}
